package com.example.applicationdataactivity;

import static android.os.storage.StorageManager.ACTION_CLEAR_APP_CACHE;
import static android.os.storage.StorageManager.ACTION_MANAGE_STORAGE;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.app.usage.StorageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    static String TAG = "ApplicationDataActivity";
    private final String fileName = "thisIsMyFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            getApplicationDir();
            writeToApplicationDirFile(this);
            getApplicationDirFile(this);
            readFromApplicationDirFile(this);
            getFileList(this);
            createFileDir(this);
            File cacheFile = createFileCache(this);
            deleteCacheFile(cacheFile);
            deleteCacheFileByName(this);
            isExternalStorageWritable();
            isExternalStorageReadable();
            choosePhysicStorage();
            getExternalFileDir(this);
            createCacheFile(this);
            getAppSpecificAlbumStorageDir(this, "myAlbum");
            searchDevicesAvailable();
            showAllocatedSpace();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                clearAllCache();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ///存储路径
    private void getApplicationDir() {
        getFilesDir();
        getCacheDir();
        getExternalFilesDir("mp4");
        getExternalCacheDir();
    }

    ///获取文件
    private void getApplicationDirFile(Context context) {
        File file = new File(context.getFilesDir(), fileName);
    }

    ///信息流存储文件
    private void writeToApplicationDirFile(Context context) throws IOException {
        String fileContents = "Hello world! 你好";
        try (FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE)) {
            fos.write(fileContents.getBytes());
        }
    }

    ///信息流访问文件
    private void readFromApplicationDirFile(Context context) throws FileNotFoundException {
        FileInputStream fis = context.openFileInput(fileName);
        InputStreamReader inputStreamReader = new InputStreamReader(fis, StandardCharsets.UTF_8);
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line).append('\n');
                line = reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String contents = stringBuilder.toString();
        }
    }

    ///查看文件列表
    private void getFileList(Context context) {
        String[] files = context.fileList();
        for (String file : files) {

        }

    }

    ///创建嵌套目录
    private void createFileDir(Context context) {
        File directory = context.getFilesDir();
        File file = new File(directory, fileName);
    }

    ///创建缓存文件
    private File createFileCache(Context context) throws IOException {
        return File.createTempFile(fileName, null, context.getCacheDir());
    }

    ///移除缓存文件
    private void deleteCacheFile(File cacheFile) {
        boolean result = cacheFile.delete();
    }

    ///移除缓存文件
    private void deleteCacheFileByName(Context context) {
        boolean result = context.deleteFile(fileName);
    }

    ///验证存储空间的可用性
    ///检查外部存储空间中是否可以读写文件
    private boolean isExternalStorageWritable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    ///至少可以读文件
    private boolean isExternalStorageReadable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    }

    ///选择物理存储位置
    private void choosePhysicStorage() {
        File[] externalStorageVolumes = ContextCompat.getExternalFilesDirs(getApplicationContext(), null);
        File primaryExternalStorage = externalStorageVolumes[0];
    }

    ///访问持久性文件
    private void getExternalFileDir(Context context) {
        File appSpecificExternalDir = new File(context.getExternalFilesDir(null), fileName);
    }

    ///创建缓存文件
    private void createCacheFile(Context context) {
        File externalCacheFile = new File(context.getExternalCacheDir(), fileName);
    }

    ///媒体内容
    File getAppSpecificAlbumStorageDir(Context context, String albumName) {
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), albumName);
        if (!file.mkdirs()) {
            Log.e(TAG, "Directory not created");
        }
        return file;
    }

    ///查询可用空间
    private void searchDevicesAvailable() throws IOException {
        long NUM_BYTES_NEEDED_FOR_MY_APP = 1024 * 1024 * 10L;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            StorageManager storageManager = getApplicationContext().getSystemService(StorageManager.class);
            UUID appSpecificInternalDirUuid = storageManager.getUuidForPath(getFilesDir());
            ///可用空间
            long availableBytes = storageManager.getAllocatableBytes(appSpecificInternalDirUuid);
            if (availableBytes >= NUM_BYTES_NEEDED_FOR_MY_APP) {
                storageManager.allocateBytes(appSpecificInternalDirUuid, NUM_BYTES_NEEDED_FOR_MY_APP);
            } else {
                ///管理存储，释放空间
                Intent storageIntent = new Intent();
                storageIntent.setAction(ACTION_MANAGE_STORAGE);
                startActivity(storageIntent);
            }
        }
    }

    ///显示设备上可用空间量
    private void showAllocatedSpace() throws IOException {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            StorageStatsManager storageStatsManager = (StorageStatsManager) getSystemService(Context.STORAGE_STATS_SERVICE);
            StorageManager storageManager = getApplicationContext().getSystemService(StorageManager.class);
            UUID appSpecificInternalDirUuid = storageManager.getUuidForPath(getFilesDir());
            long freeBytes = storageStatsManager.getFreeBytes(appSpecificInternalDirUuid);
            long totalBytes = storageStatsManager.getTotalBytes(appSpecificInternalDirUuid);
            double value = (float) freeBytes / totalBytes;
            Toast.makeText(getApplicationContext(), String.valueOf(value), Toast.LENGTH_LONG).show();
        }
    }

    ///移除所有缓文件
    @RequiresApi(api = Build.VERSION_CODES.R)
    private void clearAllCache() {
        Intent intent = new Intent();
        intent.setAction(ACTION_CLEAR_APP_CACHE);
        startActivityForResult(intent, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1000) {
            Toast.makeText(getApplicationContext(), "调用", Toast.LENGTH_LONG).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}